package com.bolingcavalry.crm.WeChatPush.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bolingcavalry.crm.WeChatPush.service.WeChatPushService;
import com.bolingcavalry.crm.user.mapper.UserMapper;
import com.bolingcavalry.crm.utils.HttpUtil;
import com.dto.TaskReviewMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class WeChatPushServiceImpl implements WeChatPushService {

    @Autowired
    private UserMapper userMapper;

    @Value("${wechat.appid:your_appid}")
    private String appId;

    @Value("${wechat.secret:your_secret}")
    private String appSecret;

    private String accessToken;
    private long tokenExpireTime;

    // 模板ID常量
    private static final String TEMPLATE_CREATE_WORK_ORDER = "SITcPF2sqzlwQ5BOKYDRlradeISVVfDdMwfVrbUZhbE"; // 创建工单通知
    private static final String TEMPLATE_WORK_ORDER_ASSIGNMENT = "wS4ylRJuo4n-9da81PCOqIaKDmul4gBUp6u2Z_XXyO4"; // 工单派工通知
    private static final String TEMPLATE_BUSINESS_REVIEW = "kt6J-EM4XwBKX0lW0YtDW0EOHN63dLK4wqJTggZ_uGE"; // 业务审核通知
    private static final String TEMPLATE_REVIEW_REJECT = "gbbqoXdEwnh4k5Q2tIu7eR6K1lZrF5pvfjbnXPeeGvU"; // 审核拒绝通知
    private static final String TEMPLATE_TASK_COMPLETE = "10xJINyxzpiNzqrlhLmyDQm4R_3KaXS1OViN-wT0xD4"; // 任务完成通知
    private static final String TEMPLATE_PROBLEM_FEEDBACK = "pIpxRVK2J9NSzoUWAuZjOexqRnpWCWZHvpebnHe2y8s"; // 问题反馈通知

    @Override
    public void pushCreateWorkOrderNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_CREATE_WORK_ORDER);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("thing1", Map.of("value", data.getOrDefault("title", "无工单信息")));
            messageData.put("time2", Map.of("value", data.getOrDefault("createTime", getCurrentTime())));
            messageData.put("thing3", Map.of("value", data.getOrDefault("businessType", "无项目信息")));
            messageData.put("thing4", Map.of("value", data.getOrDefault("senderName", "系统")));
            messageData.put("thing5", Map.of("value", data.getOrDefault("businessType", "工单类型")));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送创建工单通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushWorkOrderAssignmentNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_WORK_ORDER_ASSIGNMENT);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("character_string1", Map.of("value", data.getOrDefault("orderNumber", "无工单号")));
            messageData.put("thing2", Map.of("value", data.getOrDefault("businessType", "无客户信息")));
            messageData.put("name3", Map.of("value", data.getOrDefault("senderName", "无联系人")));
            messageData.put("phone_number4", Map.of("value", "请查看详情"));
            messageData.put("thing5", Map.of("value", data.getOrDefault("content", "无工单信息")));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送工单派工通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushBusinessReviewNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_BUSINESS_REVIEW);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("thing1", Map.of("value", data.getOrDefault("businessType", "业务类型")));
            messageData.put("time2", Map.of("value", data.getOrDefault("createTime", getCurrentTime())));
            messageData.put("phrase3", Map.of("value", "待审核"));
            messageData.put("thing4", Map.of("value", data.getOrDefault("content", "请查看详情")));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送业务审核通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushReviewRejectNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_REVIEW_REJECT);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("character_string1", Map.of("value", data.getOrDefault("orderNumber", "无工单号")));
            messageData.put("phrase2", Map.of("value", "已拒绝"));
            messageData.put("name3", Map.of("value", data.getOrDefault("senderName", "审核人")));
            messageData.put("thing4", Map.of("value", data.getOrDefault("content", "拒绝原因")));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送审核拒绝通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushTaskCompleteNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_TASK_COMPLETE);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("thing1", Map.of("value", data.getOrDefault("title", "任务名称")));
            messageData.put("character_string2", Map.of("value", data.getOrDefault("orderNumber", "无工单号")));
            messageData.put("name3", Map.of("value", data.getOrDefault("senderName", "完成人")));
            messageData.put("time4", Map.of("value", data.getOrDefault("createTime", getCurrentTime())));
            messageData.put("thing5", Map.of("value", data.getOrDefault("content", "任务描述")));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送任务完成通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushProblemFeedbackNotice(String openid, Map<String, String> data) {
        try {
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("touser", openid);
            templateData.put("template_id", TEMPLATE_PROBLEM_FEEDBACK);

            Map<String, Map<String, String>> messageData = new HashMap<>();
            messageData.put("thing1", Map.of("value", data.getOrDefault("businessType", "问题类型")));
            messageData.put("thing2", Map.of("value", data.getOrDefault("content", "问题描述")));
            messageData.put("name3", Map.of("value", data.getOrDefault("senderName", "反馈人")));
            messageData.put("phrase4", Map.of("value", "待处理"));
            messageData.put("time5", Map.of("value", data.getOrDefault("createTime", getCurrentTime())));

            templateData.put("data", messageData);
            sendMessage(templateData);
        } catch (Exception e) {
            log.error("推送问题反馈通知失败, openid: {}", openid, e);
        }
    }

    @Override
    public void pushMessageByMessageType(String openid, TaskReviewMessageDTO dto) {
        try {
            // 构造模板数据
            Map<String, String> templateData = new HashMap<>();
            templateData.put("title", dto.getTitle() != null ? dto.getTitle() : "无标题");
            templateData.put("content", dto.getContent() != null ? dto.getContent() : "无内容");
            templateData.put("orderNumber", dto.getOrderNumber() != null ? dto.getOrderNumber() : "无单号");
            templateData.put("senderName", dto.getSenderName() != null ? dto.getSenderName() : "系统");
            templateData.put("businessType", dto.getBusinessType() != null ? dto.getBusinessType() : "业务类型");
            templateData.put("createTime", getCurrentTime());

            String messageType = dto.getMessageType();
            if (messageType == null || messageType.isEmpty()) {
                messageType = "PROBLEM_FEEDBACK"; // 默认使用问题反馈模板
            }

            switch (messageType) {
                case "CREATE_WORK_ORDER":
                    pushCreateWorkOrderNotice(openid, templateData);
                    break;
                case "WORK_ORDER_ASSIGNMENT":
                    pushWorkOrderAssignmentNotice(openid, templateData);
                    break;
                case "BUSINESS_REVIEW":
                    pushBusinessReviewNotice(openid, templateData);
                    break;
                case "REVIEW_REJECT":
                    pushReviewRejectNotice(openid, templateData);
                    break;
                case "TASK_COMPLETE":
                    pushTaskCompleteNotice(openid, templateData);
                    break;
                case "PROBLEM_FEEDBACK":
                    pushProblemFeedbackNotice(openid, templateData);
                    break;
                default:
                    // 默认推送问题反馈通知
                    pushProblemFeedbackNotice(openid, templateData);
                    log.warn("未知的消息类型: {}, 使用默认模板推送", messageType);
                    break;
            }
        } catch (Exception e) {
            log.error("根据消息类型推送微信消息失败, openid: {}, messageType: {}", openid, dto.getMessageType(), e);
        }
    }

    /**
     * 发送消息
     */
    private void sendMessage(Map<String, Object> messageData) throws Exception {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

        String jsonData = JSON.toJSONString(messageData);
        String response = HttpUtil.post(url, jsonData);

        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.getIntValue("errcode") != 0) {
            log.error("微信消息发送失败: {}", response);
            throw new Exception("微信消息发送失败: " + response);
        }

        log.info("微信消息发送成功: {}", response);
    }

    @Override
    public String getAccessToken() throws Exception {
        // 检查token是否过期
        if (accessToken != null && System.currentTimeMillis() < tokenExpireTime) {
            return accessToken;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + appSecret;

        String response = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.containsKey("access_token")) {
            accessToken = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getIntValue("expires_in");
            tokenExpireTime = System.currentTimeMillis() + (expiresIn - 300) * 1000; // 提前5分钟刷新
            log.info("获取微信access_token成功");
            return accessToken;
        } else {
            log.error("获取access_token失败: {}", response);
            throw new Exception("获取access_token失败: " + response);
        }
    }

    private String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}